import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    gridItems: [],
    isShow: true, //是否显示数字
    valueIcon: [], //点击的箭头
    totalCount: 0, //题目总数
    count: 0, //记录做题次数
    isExercise: true, //是否是练习题
    arrowItems: [{
        icon: '../../img/arrow-up.png',
        id: 1
      },
      {
        icon: '../../img/arrow-left.png',
        id: 2
      },
      {
        icon: '../../img/arrow-down.png',
        id: 3
      },
      {
        icon: '../../img/arrow-right.png',
        id: 4
      },
      {
        icon: '../../img/clear.png',
        id: 'delete',
        value: 'delete',
      }
    ],
    clickedOrder: [], // 记录点击的箭头 id 顺序
    countdownTime: 10, // 倒计时时间
    countdownInterval: null, // 存储 interval ID
    questionIndex: 0, //当前题型索引
    isShowTip: false, //练习结束提示
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
  },
  onLoad() {
    this.generateCode();
    this.getTopicData();
     // 初始化时加载已有的答题记录
     const savedAnswerRecords = answerUtil.getAnswerRecords();
     this.setData({
       answerRecords: savedAnswerRecords
     });
  },
  // 获取题目数量
  getTopicData() {
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {count} = util.getData(questionIndex);
    this.setData({
      totalCount: count,
      questionIndex
    })
  },
  // 生成四个随机数
  generateCode() {
    const numbers = [1, 2, 3, 4];
    const shuffled = numbers.sort(() => Math.random() - 0.5);
    const code = parseInt(shuffled.join(''), 10);
    const digits = shuffled.map(num => num.toString());
    const {arrowItems} = this.data;
    // 遍历 arrowItems，为前四项插入 digits 的值
    const mergedArrowItems = arrowItems.map((item, index) => {
      if (index < digits.length && item.id !== 'delete') {
        return {
          ...item,
          value: digits[index] // 插入对应的 digit 值
        };
      }
      return item; // delete 项保持原样
    });
    this.setData({
      gridItems: shuffled.map(num => ({num: num.toString()})),
      code: String(code),
      valueIcon: '', // 清空上次输入
      isShow: true,
      arrowItems: mergedArrowItems,
      clickedOrder: [],
    });

    setTimeout(() => {
      this.setData({
        isShow: false
      });
      // 每道题目开始倒计时
      this.startCountdown();
      this.setData({
        questionStartTime: new Date().getTime()
      })
    }, 3000);
  },
  // 倒计时
  startCountdown() {
    const that = this;
    let {totalCount,count,isExercise} = that.data;
    // 清除已有倒计时
    if (that.data.countdownInterval) {
      clearInterval(that.data.countdownInterval);
    }
    that.setData({
      countdownTime: 10
    });
    const interval = setInterval(() => {
      const newTime = that.data.countdownTime - 1;
      if (newTime > 0) {
        that.setData({
          countdownTime: newTime
        });
      } else {
        clearInterval(interval);
        // 倒计时结束，视为错误
        wx.showToast({
          title: '已超时',
          icon: 'none',
          duration: 1000
        });
        setTimeout(() => {
          if (isExercise) {
            that.generateCode();
          } else {
            // 使用共用方法创建并保存答题记录
            const newAnswerRecords = this.createAndSaveAnswerRecord(true);
            // 无论对错都增加总次数
            let countNum = count + 1;
            that.setData({
              count:countNum,
              answerRecords: newAnswerRecords
            })
            // 判断题目次数，跳转并打印结果
            if (countNum >= totalCount) {
              //跳转下一题
              let questionNumber = that.data.questionIndex + 1;
              const prevInfo = wx.getStorageSync('questionInfo') || {};
              wx.setStorageSync('questionInfo', {
                ...prevInfo,
                questionNumber
              });
              util.navigateByDesc(questionNumber);
            } else {
              // 继续下一题
              that.generateCode();
            }
          }
        }, 1000);
      }
    }, 1000);
    that.setData({
      countdownInterval: interval
    });
  },

  // 点击按钮
  onTap(e) {
    const icon = e.currentTarget.dataset.icon;
    const value = e.currentTarget.dataset.value;
    let currentValue = this.data.valueIcon;
    let currentOrder = this.data.clickedOrder;
    if (value === 'delete') {
      const newValue = currentValue.slice(0, -1);
      const newOrder = currentOrder.slice(0, -1); // 删除最后一个点击记录
      this.setData({
        valueIcon: newValue,
        clickedOrder: newOrder
      });
    } else if (currentValue.length < 4) {
      this.setData({
        valueIcon: [...this.data.valueIcon, icon],
        clickedOrder: [...this.data.clickedOrder, value] // 记录点击的 value
      });
    }
  },
  // 提交
  onSubmit() {
    const {totalCount,clickedOrder} = this.data;
    if (!clickedOrder.length) return;
    let {count,isExercise} = this.data;
    // 正确顺序应为 ["1", "2", "3", "4"]
    const correctOrder = ["1", "2", "3", "4"];
    // 判断长度是否为 4 且每一项都匹配
    const isCorrect = clickedOrder.length === 4 &&
      clickedOrder.every((item, index) => item === correctOrder[index]);
    // 如果是练习题，正确的话提示练习结束开始测试，错误的话一直更新题目，如果不是练习题，记录做题次数
    if (isExercise) {
      if (isCorrect) {
        this.setData({
          isExercise: false,
          isShowTip: true
        })
      } else {
        wx.showToast({
          title: '错误',
          icon: 'none',
          duration: 1000
        });
        setTimeout( () => {
          this.generateCode();
        },1000)
      }
    } else {
      // 使用共用方法创建并保存答题记录
      const newAnswerRecords = this.createAndSaveAnswerRecord(false, clickedOrder.toString(),isCorrect);
      // 无论对错都增加总次数
      let countNum = count + 1;
      this.setData({
        count:countNum,
        answerRecords: newAnswerRecords
      })
      // 判断题目次数，跳转并打印结果
      if (countNum >= totalCount) {
        //跳转下一题
        let questionNumber = this.data.questionIndex + 1;
        const prevInfo = wx.getStorageSync('questionInfo') || {};
        wx.setStorageSync('questionInfo', {
          ...prevInfo,
          questionNumber
        });
        util.navigateByDesc(questionNumber);
      } else {
        // 继续下一题
        this.generateCode();
      }
    }
    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
    }
  },
  // 开始测试
  onStar() {
    this.setData({
      isShowTip: false,
    })
    this.generateCode();
  },
  // 处理答题记录
  createAndSaveAnswerRecord(isTimeout = false, userOption = '',isRight = false) {
    const {questionStartTime,questionIndex} = this.data;
    const questionList = wx.getStorageSync('questionInfo').questionList;
    const currentTopic = questionList[questionIndex]
    // 计算答题时间
    const endTime = new Date().getTime();
    const answerTime = answerUtil.calculateAnswerTime(questionStartTime, endTime);

    // 判断是否正确（超时视为错误）
    let option = '';
    if (!isTimeout) {
      option = userOption;
      isRight = isRight ? 1 : 0;
    }
    
    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: 0,
      anserTime: answerTime,
      isRight: isRight,
      option: option,
      classify: currentTopic.typeCode,
      stem: '',
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: '',
      score: 0,
    });
    
    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);
    
    return newAnswerRecords;
  },

  onUnload() {
    // 页面卸载时确保答题记录已保存
    answerUtil.saveAnswerRecords(this.data.answerRecords);
    // 清除定时器
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
  }
})